package ar.com.juanlopezcervero.flexigrid4j.paging.hibernate;

import ar.com.juanlopezcervero.flexigrid4j.page.GridFilterDTO;

public class GridFilterUtils {

	public static Criteria applyFilter(GridFilterDTO filtro,
			Criteria criteria) {
		
		criteria = applyFilterWithoutPaging(filtro, criteria);
		
		
		if (filtro != null) {
			if (filtro.getSortName() != null && !filtro.getSortName().trim().isEmpty()) {
				if (filtro.getSortOrder() != null && filtro.getSortOrder().equals("desc")) {				
					criteria.addOrder(Order.desc(filtro.getSortName()));
				} else {
					criteria.addOrder(Order.asc(filtro.getSortName()));
				}
			}
			//paging
			criteria.setFirstResult((filtro.getPage() - 1) * filtro.getNumberOfRecords());
			criteria.setMaxResults(filtro.getNumberOfRecords());
		}
		return criteria;
	}
	
	public static Criteria applyFilterWithoutPaging(GridFilterDTO filtro,
			Criteria criteria) {
		
		if (filtro != null) {
		
			if (filtro.getQuery() != null && !filtro.getQuery().trim().isEmpty()) {
				String column = filtro.getColumFilter();
				criteria.add(Restrictions.ilike(column, filtro.getQuery(), MatchMode.ANYWHERE));
			}
			
			
		}
		return criteria;
		
	}

}
